#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "los_task.h"

#define BUFFER_SIZE 5U

UINT32 g_taskHiId;
UINT32 g_taskLoId;
#define TSK_PRIOR_HI 4
#define TSK_PRIOR_LO 5
UINT32 Example_TaskHi(VOID)
{
    UINT32 ret;
    printf("Enter TaskHi Handler.\n");
    /* 延时100个Ticks，延时后该任务会挂起，执行剩余任务
    中最高优先级的任务(TaskLo任务) */
    ret = LOS_TaskDelay(100);
    if (ret != LOS_OK)
    {
    printf("Delay TaskHi Failed.\n");
    return LOS_NOK;
    }
    /* 100个Ticks时间到了后，该任务恢复，继续执行 */
    printf("TaskHi LOS_TaskDelay Done.\n");
    /* 挂起自身任务 */
    ret = LOS_TaskSuspend(g_taskHiId);
    if (ret != LOS_OK)
    {
    printf("Suspend TaskHi Failed.\n");
    return LOS_NOK;
    }
    printf("TaskHi LOS_TaskResume Success.\n");
    return ret;
}

UINT32 Example_TaskLo(VOID)
{
    UINT32 ret;
    printf("Enter TaskLo Handler.\n");
    /* 延时100个Ticks，延时后该任务会挂起，执行剩余
    任务中最高优先级的任务 */
    ret = LOS_TaskDelay(100);
    if (ret != LOS_OK)
    {
    printf("Delay TaskLo Failed.\n");
    return LOS_NOK;
    }
    printf("TaskHi LOS_TaskSuspend Success.\n");
    /* 恢复被挂起的任务g_taskHiId */
    ret = LOS_TaskResume(g_taskHiId);
    if (ret != LOS_OK)
    {
    printf("Resume TaskHi Failed.\n");
    return LOS_NOK;
    }
    return ret;
}

static void Example_TskCaseEntry(void)
{
    UINT32 ret;
    TSK_INIT_PARAM_S initParam;
    /* 锁任务调度，防止新创建的任务比本任务高而发生调度 */
    LOS_TaskLock();
    printf("LOS_TaskLock() Success!\n");
    initParam.pfnTaskEntry =
    (TSK_ENTRY_FUNC)Example_TaskHi;
    initParam.usTaskPrio = TSK_PRIOR_HI;
    initParam.pcName = "TaskHi";
    initParam.uwStackSize =
    LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
    /* 创建高优先级任务，由于锁任务调度，任务创建成功后不会马
    上执行 */
    ret = LOS_TaskCreate(&g_taskHiId, &initParam);
    if (ret != LOS_OK)
    {
        LOS_TaskUnlock();
        printf("Example_TaskHi create Failed!\n");
        return;
    }
    printf("Example_TaskHi create Success!\n");
    initParam.pfnTaskEntry =
    (TSK_ENTRY_FUNC)Example_TaskLo;
    initParam.usTaskPrio = TSK_PRIOR_LO;
    initParam.pcName = "TaskLo";
    initParam.uwStackSize =
    LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
    /* 创建低优先级任务，由于锁任务调度，任务创建成功后不会马
    上执行 */
    ret = LOS_TaskCreate(&g_taskLoId, &initParam);
    if (ret != LOS_OK)
    {
        LOS_TaskUnlock();
        printf("Example_TaskLo create Failed!\n");
        return;
    }
    printf("Example_TaskLo create Success!\n");
    /* 解锁任务调度，此时会发生任务调度，执行就绪队列中最高优
    先级任务 */
    LOS_TaskUnlock();
}
APP_FEATURE_INIT(Example_TskCaseEntry);